<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>后台管理系统</h2>
        <p class="welcome-text">欢迎回来，请登录您的账号</p>
      </div>
      <el-form ref="loginFormRef" :model="loginForm" :rules="rules" class="login-form" @keyup.enter="submitForm">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" :prefix-icon="User" clearable
            @focus="handleInputFocus" @blur="handleInputBlur" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" show-password
            clearable @focus="handleInputFocus" @blur="handleInputBlur" />
        </el-form-item>
        <div class="form-options">
          <el-checkbox v-model="loginForm.remember">记住密码</el-checkbox>
          <el-link type="primary" :underline="false">忘记密码？</el-link>
        </div>
        <el-form-item>
          <el-button :loading="loading" type="primary" class="login-button" @click="submitForm">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
        <!-- <div class="register-link">
          还没有账号？
          <el-link type="primary" :underline="false" @click="goToRegister">
            立即注册
          </el-link>
        </div> -->
      </el-form>
    </div>
    <!-- 背景动画 -->
    <div class="circles">
      <div v-for="n in 10" :key="n" :class="'circle-' + n"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { login } from '../api/login'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  remember: false
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ]
}

const submitForm = async () => {
  try {
    await loginFormRef.value.validate()
    
    // 显示加载状态
    loading.value = true
    
    try {
      // 调用登录API
      const res = await login({
        username: loginForm.username,
        password: loginForm.password
      })
      
      console.log('登录响应:', res)
      
      // 处理登录成功
      if (res.success === true || (res.code === 200)) {
        // 存储用户信息和token
        const userData = res.data || {}
        const token = userData.token || ''
        
        if (!token) {
          ElMessage.error('登录成功但未获取到Token，请联系管理员')
          loading.value = false
          return
        }
        
        // 保存到本地存储
        localStorage.setItem('token', token)
        localStorage.setItem('user', JSON.stringify(userData))
        
        console.log('Token已保存:', token)
        
        ElMessage.success('登录成功')
        
        // 延迟跳转，确保token已被保存和应用
        setTimeout(() => {
          // 跳转到首页
          router.replace('/')
        }, 500)
      } else {
        // 显示错误信息
        ElMessage.error(res.msg || res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录请求出错:', error)
      ElMessage.error(error.message || '登录失败，请稍后重试')
    } finally {
      // 无论结果如何，都关闭加载状态
      loading.value = false
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const goToRegister = () => {
  router.push('/register')
}

const handleInputFocus = (e) => {
  e.target.parentElement.classList.add('focused')
}

const handleInputBlur = (e) => {
  e.target.parentElement.classList.remove('focused')
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

.login-container::before {
  content: '';
  position: absolute;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 1;
  transform: translateY(0);
  transition: transform 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px);
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.login-header h2 {
  margin: 0;
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 10px;
}

.welcome-text {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.login-form {
  margin-top: 20px;
}

:deep(.el-input__wrapper) {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

:deep(.el-input__wrapper.focused) {
  background-color: #fff;
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
  font-size: 14px;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 42px;
  font-size: 16px;
  border-radius: 21px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.login-button:active {
  transform: translateY(0);
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

:deep(.el-checkbox__label) {
  color: #666;
}

:deep(.el-link) {
  font-size: 14px;
}

:deep(.el-form-item__error) {
  padding-top: 4px;
  font-size: 12px;
}

/* 背景动画 */
.circles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

@keyframes animate {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 1;
    border-radius: 0;
  }

  100% {
    transform: translateY(-1000px) rotate(720deg);
    opacity: 0;
    border-radius: 50%;
  }
}

.circles div {
  position: absolute;
  display: block;
  width: 20px;
  height: 20px;
  background: rgba(255, 255, 255, 0.2);
  animation: animate 25s linear infinite;
  bottom: -150px;
}

.circle-1 {
  left: 25%;
  width: 80px;
  height: 80px;
  animation-delay: 0s;
}

.circle-2 {
  left: 10%;
  width: 20px;
  height: 20px;
  animation-delay: 2s;
  animation-duration: 12s;
}

.circle-3 {
  left: 70%;
  width: 20px;
  height: 20px;
  animation-delay: 4s;
}

.circle-4 {
  left: 40%;
  width: 60px;
  height: 60px;
  animation-delay: 0s;
  animation-duration: 18s;
}

.circle-5 {
  left: 65%;
  width: 20px;
  height: 20px;
  animation-delay: 0s;
}

.circle-6 {
  left: 75%;
  width: 110px;
  height: 110px;
  animation-delay: 3s;
}

.circle-7 {
  left: 35%;
  width: 150px;
  height: 150px;
  animation-delay: 7s;
}

.circle-8 {
  left: 50%;
  width: 25px;
  height: 25px;
  animation-delay: 15s;
  animation-duration: 45s;
}

.circle-9 {
  left: 20%;
  width: 15px;
  height: 15px;
  animation-delay: 2s;
  animation-duration: 35s;
}

.circle-10 {
  left: 85%;
  width: 150px;
  height: 150px;
  animation-delay: 0s;
  animation-duration: 11s;
}
</style>